package com.tebiecloud.mpweixin.server.listener;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.google.common.collect.Lists;
import com.tebiecloud.common.constants.ResultEnum;
import com.tebiecloud.common.model.ResultBody;
import com.tebiecloud.common.utils.DigitUtils;
import com.tebiecloud.common.utils.JsonUtils;
import com.tebiecloud.common.utils.StringUtils;
import com.tebiecloud.mpweixin.client.constants.QueueConstants;
import com.tebiecloud.mpweixin.client.model.entity.MpweixinUser;
import com.tebiecloud.mpweixin.client.model.mpweixin.*;
import com.tebiecloud.mpweixin.server.properties.MpweixinProperties;
import com.tebiecloud.mpweixin.server.service.MpweixinUserService;
import com.tebiecloud.mpweixin.server.service.feign.MpopenApiServiceClient;
import com.tebiecloud.mpweixin.server.service.feign.OrderServiceClient;
import com.tebiecloud.mpweixin.server.service.feign.StoreServiceClient;
import com.tebiecloud.mpweixin.server.utils.MPApi;
import com.tebiecloud.order.client.constatns.OrderConstants;
import com.tebiecloud.order.client.model.entity.Orderr;
import com.tebiecloud.store.client.model.entity.Store;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.handler.annotation.Payload;

import java.util.List;

/**
 * 监听公众号消息事件
 * @Author: tebie
 * @Date: 2019-10-07 17:21
 */
@Slf4j
@Configuration
public class MpweixinEventInfoListener {

    @Autowired
    private MpweixinProperties mpweixinProperties;

    @Autowired
    private MpweixinUserService mpweixinUserService;

    @Autowired
    private MpopenApiServiceClient mpopenApiServiceClient;

    @Autowired
    private OrderServiceClient orderServiceClient;

    @Autowired
    private StoreServiceClient storeServiceClient;

    /**
     * 接收公众号消息事件
     * @param info
     */
    @RabbitListener(queues = QueueConstants.QUEUE_MPWEIXIN_EVENT_INFO)
    public void ScanApiResourceQueue(@Payload MPReceiveEventInfo info) {
        try {
            if("subscribe".equalsIgnoreCase(info.getEvent())) { // 订阅
                MpweixinUser mpweixinUser = new MpweixinUser();
                mpweixinUser.setOpenid(info.getFromUserName());
                mpweixinUser.setSubscribe(1);
                UpdateWrapper<MpweixinUser> updateWrapper = new UpdateWrapper<>();
                updateWrapper.eq("openid", info.getFromUserName());
                mpweixinUserService.update(mpweixinUser, updateWrapper);

                // 如果通过扫描关注的，会有值：EventKey，Ticket
                String eventKey = info.getEventKey();
                if(!StringUtils.isEmpty(eventKey) && !"[]".equals(eventKey)) {
                    if(eventKey.startsWith("qrscene_")) {
                        scanQrcode(info.getFromUserName(), eventKey.substring("qrscene_".length(), eventKey.length()));
                    } else {
                        log.info("xiaoc>> 公众号事件处理线程，通过扫描关注判断eventKey值失败，info: {}", JsonUtils.Obj2Str(info));
                    }
                }
            } else if("unsubscribe".equalsIgnoreCase(info.getEvent())) { // 取消订阅
                MpweixinUser mpweixinUser = new MpweixinUser();
                mpweixinUser.setSubscribe(0);
                UpdateWrapper<MpweixinUser> updateWrapper = new UpdateWrapper<>();
                updateWrapper.eq("openid", info.getFromUserName());
                mpweixinUserService.update(mpweixinUser, updateWrapper);
            } else if("scan".equalsIgnoreCase(info.getEvent())) { // 扫描二维码
                scanQrcode(info.getFromUserName(), info.getEventKey());
            } else {
                // 其它事件不处理
                if(!"LOCATION".equalsIgnoreCase(info.getEvent())) { // 定位信息太多，不打印
                    log.debug("xiac>> 公众号事件处理线程，忽略的消息类型, info: {}", JsonUtils.Obj2Str(info));
                }
            }
        } catch (Exception e) {
            log.error("error:", e);
        }
    }

    /**
     * 扫描二维码处理
     * @param openid
     * @param sceneStr
     */
    private void scanQrcode(String openid, String sceneStr) {
        // 指定了测试人员，且不在测试列表的，不处理
        if(!StringUtils.isEmpty(mpweixinProperties.getTestOpenids()) && !mpweixinProperties.getTestOpenids().contains(openid)) {
            log.info("xiaoc>> 跳过扫描二维码处理，不在测试列表中, openid: {}, testOpenids: {}", openid, mpweixinProperties.getTestOpenids());
            return ;
        }

        // 扫描的是订单二维码
        if(sceneStr.startsWith(OrderConstants.ORDER_QRCODE_SCENESTR_)) {
            long orderId = DigitUtils.str2Long(sceneStr.replace(OrderConstants.ORDER_QRCODE_SCENESTR_, ""), -1);
            if(orderId > 0) {
                // 订单信息
                ResultBody<Orderr> resOrderr = orderServiceClient.selectOrder(orderId);
                if(resOrderr.getCode() == ResultEnum.OK.getCode()) {
                    Orderr order = resOrderr.getData();

                    // 获取门店信息
                    ResultBody<Store> resStore = storeServiceClient.getStore(order.getStoreId());
                    Store store = null;
                    if(resStore.getCode() == ResultEnum.OK.getCode()) {
                        store = resStore.getData();
                    }

                    // 推送订单信息
                    SendMpMsgInfo sendMpMsgInfo = new SendMpMsgInfo();
                    sendMpMsgInfo.setTouser(openid);

//                    sendMpMsgInfo.setMsgtype("text");
//                    Text text = new Text();
//                    if(order.getStatus() == 1) {
//                        text.setContent("https://tebie.gzqqs.com/pic/#/BsubmitOrder?orderId=" + orderId);
//                    } else {
//                        text.setContent("https://tebie.gzqqs.com/pic/#/orderDetail?orderId=" + orderId);
//                    }
//                    sendMpMsgInfo.setText(text);

                    sendMpMsgInfo.setMsgtype("news");
                    News news = new News();
                    Article article = new Article();
                    article.setDescription(store != null ? store.getName() : "");
                    if(order.getStatus() == 1) {
                        article.setTitle(mpweixinProperties.getOrderNewsTitle());
                        article.setUrl(mpweixinProperties.getOrderNewsUrl1() + "=" + orderId);
                    } else {
                        article.setTitle(mpweixinProperties.getOrderNewsTowTitle());
                        article.setUrl(mpweixinProperties.getOrderNewsUrl2() + "=" + orderId);
                    }
                    article.setPicurl(mpweixinProperties.getOrderNewsPicurl());
                    List<Article> articles = Lists.newArrayList();
                    articles.add(article);
                    news.setArticles(articles);
                    sendMpMsgInfo.setNews(news);

                    String appid = mpweixinProperties.getAppid();
                    ResultBody<String> respAccessToekn = mpopenApiServiceClient.getWxapiAccessToken(appid, false);
                    if(respAccessToekn.getCode() != ResultEnum.OK.getCode()) {
                        log.info("发送微信消息失败, respAccessToekn: {}", JsonUtils.Obj2Str(respAccessToekn));
                    } else {
                        MPApi.postMessageCustom(respAccessToekn.getData(), JsonUtils.Obj2Str(sendMpMsgInfo));
                    }
                } else {
                    log.info("订单不存在");
                }
            }
        } else if(sceneStr.startsWith(OrderConstants.STORE_QRCODE_SCENESTR_)) { // 扫描门店二维码
            long storeId = DigitUtils.str2Long(sceneStr.replace(OrderConstants.STORE_QRCODE_SCENESTR_, ""), -1);
            if(storeId > 0) {
                // 获取门店信息
                ResultBody<Store> resStore = storeServiceClient.getStore(storeId);
                Store store = null;
                if(resStore.getCode() == ResultEnum.OK.getCode()) {
                    store = resStore.getData();
                }

                // 推送订单信息
                SendMpMsgInfo sendMpMsgInfo = new SendMpMsgInfo();
                sendMpMsgInfo.setTouser(openid);
                sendMpMsgInfo.setMsgtype("news");
                News news = new News();
                Article article = new Article();
                article.setDescription(mpweixinProperties.getStoreNewsDescription());
                article.setTitle(mpweixinProperties.getStoreNewsTitle() + (store.getName() != null ? store.getName() : ""));
                article.setUrl(mpweixinProperties.getStoreNewsUrl() + "=" + storeId);
                article.setPicurl(mpweixinProperties.getStoreNewsPicurl());
                List<Article> articles = Lists.newArrayList();
                articles.add(article);
                news.setArticles(articles);
                sendMpMsgInfo.setNews(news);

                String appid = mpweixinProperties.getAppid();
                ResultBody<String> respAccessToekn = mpopenApiServiceClient.getWxapiAccessToken(appid, false);
                if(respAccessToekn.getCode() != ResultEnum.OK.getCode()) {
                    log.info("发送微信消息失败, respAccessToekn: {}", JsonUtils.Obj2Str(respAccessToekn));
                } else {
                    MPApi.postMessageCustom(respAccessToekn.getData(), JsonUtils.Obj2Str(sendMpMsgInfo));
                }
            }
        } else if(sceneStr.startsWith(OrderConstants.RESERVE_QRCODE_SCENESTR_)) { // 扫描预约订单二维码
            long reserveId = DigitUtils.str2Long(sceneStr.replace(OrderConstants.RESERVE_QRCODE_SCENESTR_, ""), -1);
            if(reserveId > 0) {
                // 推送订单信息
                SendMpMsgInfo sendMpMsgInfo = new SendMpMsgInfo();
                sendMpMsgInfo.setTouser(openid);
                sendMpMsgInfo.setMsgtype("news");
                News news = new News();
                Article article = new Article();
                article.setDescription("");
                article.setTitle(mpweixinProperties.getReserveNewsTitle());
                article.setUrl(mpweixinProperties.getReserveNewsUrl() + "=" + reserveId);
                article.setPicurl(mpweixinProperties.getReserveNewsPicurl());
                List<Article> articles = Lists.newArrayList();
                articles.add(article);
                news.setArticles(articles);
                sendMpMsgInfo.setNews(news);

                String appid = mpweixinProperties.getAppid();
                ResultBody<String> respAccessToekn = mpopenApiServiceClient.getWxapiAccessToken(appid, false);
                if(respAccessToekn.getCode() != ResultEnum.OK.getCode()) {
                    log.info("发送微信消息失败, respAccessToekn: {}", JsonUtils.Obj2Str(respAccessToekn));
                } else {
                    MPApi.postMessageCustom(respAccessToekn.getData(), JsonUtils.Obj2Str(sendMpMsgInfo));
                }
            }
        }
    }

}
